package com.zhehekeji.opsys.api.service;

import java.util.Date;

import org.apache.cxf.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhehekeji.opsys.api.code.LuckyDrawResultCode;
import com.zhehekeji.opsys.api.common.util.DateFormatUtil;
import com.zhehekeji.opsys.api.conf.Config;
import com.zhehekeji.opsys.api.enm.CardDetailStatus;
import com.zhehekeji.opsys.api.enm.PrizeType;
import com.zhehekeji.opsys.api.entity.TActivity;
import com.zhehekeji.opsys.api.entity.TCardDetail;
import com.zhehekeji.opsys.api.entity.TCardInfo;
import com.zhehekeji.opsys.api.entity.TPrize;
import com.zhehekeji.opsys.api.entity.TUser;
import com.zhehekeji.opsys.api.entity.TWinningResult;
import com.zhehekeji.opsys.api.resp.LuckyDrawResp;
import com.zhehekeji.opsys.api.service.validate.args.LuckyDrawArgs;

/**
 * @ClassName PrizeService
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2015-4-13   上午10:45:59
 */
@Service
public class PrizeService extends CommonService{
	
	private final static Logger logger = LoggerFactory.getLogger(PrizeService.class);
	
	@Autowired
	private Config config;
	
	public void luckyDraw(LuckyDrawArgs luckyDrawArgs)
			throws Exception {
		 LuckyDrawResp resp = luckyDrawArgs.getResp();
		 TPrize tmpTPrize = luckyDrawArgs.getTprize();
		 Integer tmpLimitNum = tmpTPrize.getLimitNum();//是否限制数量：1-限制；0-不限制
		 Integer tmpWinningNum = tmpTPrize.getWinningNum();//奖品已中数量
		 Integer tmpNumber = tmpTPrize.getNumber();//奖品数量
		 Integer tmpLevel = tmpTPrize.getLevel();//奖品等级
		 String tmpPrizeName = tmpTPrize.getName();
		 Integer tmpPrizeType = tmpTPrize.getType();//奖品类型 1：充值卡；2：其他
		 Integer tmpPrice = tmpTPrize.getPrice();//单个奖品价格
		 String tmpPrizeCode = tmpTPrize.getCode();
		 String tmpPrizePicture = tmpTPrize.getPicture();
		 TUser tmpTUser = luckyDrawArgs.getTuser();
		 String tmpMobile = tmpTUser.getMobile();
		 String tmpAccount = tmpTUser.getAccount();
		 
		 TActivity tmpTActivity = luckyDrawArgs.getTactivity();
		 Long tmpCpCode = tmpTActivity.getCpCode();
		 Long tmpTActivityId = tmpTActivity.getId();
		 
		 Date currentDate = luckyDrawArgs.getCurrentDate();
		 String tmpStrCurrentTime = DateFormatUtil.format(currentDate, "yyyy-MM-dd HH:mm:ss");
		 String tmpStrCurrentDate = DateFormatUtil.format(currentDate, "yyyy-MM-dd");
		 
		 logger.info("奖品是否限制数量：1-限制；0-不限制，limitNum"+tmpLimitNum+",奖品总数量:"+tmpNumber+"奖品已中数量:"+tmpWinningNum+",奖品类型："+tmpPrizeType+",活动："+tmpTActivity.getName()+",奖品:"+tmpPrizeName+",用户："+tmpAccount);
		 
		 if (tmpLimitNum == 1){
			 if (tmpNumber <= tmpWinningNum){
				 logger.info("奖品已中数量小于总数量，谢谢参与！");
				 resp.setResultCode(LuckyDrawResultCode.THANK_YOU_IN);
				 resp.setResultDesc("奖品已中数量小于总数量，谢谢参与！");
				 return;
			 }
		 }
		 
		 TWinningResult tmpTWinningResult = new TWinningResult();
		 
		 if (tmpPrizeType == PrizeType.PREPAID_PHONE_CARD.getType()){
			 TCardDetail tmpTCardDetail = entityDao.get(TCardDetail.class,
					 "o.faceValue=?1 and o.status=?2 and o.tactivity.id=?3 and o.cpCode=?4 and o.expireDate>='" + tmpStrCurrentDate + "'", 
					 new Object[]{tmpPrice, CardDetailStatus.NOT_USED.getStatus(), tmpTActivityId, tmpCpCode});
			 if (tmpTCardDetail == null){
				 logger.info("没有活动的卡片，谢谢参与！");
				 resp.setResultCode(LuckyDrawResultCode.THANK_YOU_IN);
				 resp.setResultDesc("没有活动的卡片，谢谢参与！");
				 return;
			 }
			 //返回卡密
			 resp.setCardPwd(tmpTCardDetail.getCardPwd());
			 /**
			 * 绑定账户
			 */
			 tmpTCardDetail.setAccount(tmpAccount);
			 /**
			  * 更新卡状态为已使用
			  */
			 tmpTCardDetail.setStatus(CardDetailStatus.BEEN_USED.getStatus());
			 entityDao.update(tmpTCardDetail);
			 /**
			  * 更新卡已使用数量
			  */
			 TCardInfo tmpTCardInfo = tmpTCardDetail.getTcardInfo();
			 if (tmpTCardInfo != null ){
				 Integer tmpUseCount = tmpTCardInfo.getUseCount();
				 tmpUseCount = tmpUseCount == null ? 1 : tmpUseCount + 1;
				 tmpTCardInfo.setUseCount(tmpUseCount);
				 entityDao.update(tmpTCardInfo);
			 }
			 tmpTWinningResult.setCardNo(tmpTCardDetail.getCardNo());
			 tmpTWinningResult.setCardPwd(tmpTCardDetail.getCardPwd());
		 }
		 /**
		  * 更新奖品中奖数量
		  */
		 tmpWinningNum = tmpWinningNum + 1;
		 tmpTPrize.setWinningNum(tmpWinningNum);
		 entityDao.update(tmpTPrize);
		 
		 /**
		  * 保存中奖结果
		  */
		 tmpTWinningResult.setAccount(tmpAccount);
		 tmpTWinningResult.setMobile(tmpMobile);
		 tmpTWinningResult.setCpCode(tmpCpCode);
		 tmpTWinningResult.setTactivity(tmpTActivity);
		 tmpTWinningResult.setTprize(tmpTPrize);
		 tmpTWinningResult.setWinningTime(currentDate);
		 Long tmpTWinningResultId = entityDao.saveObj(tmpTWinningResult);
		 
		 resp.setPrizeType(tmpPrizeType);
		 resp.setMobile(tmpMobile);
		 resp.setPrizeLevel(tmpLevel);
		 resp.setPrizeName(tmpPrizeName);
		 resp.setUserID(tmpAccount);
		 resp.setWinningTime(tmpStrCurrentTime);
		 resp.setPrizePrice(tmpPrice);
		 resp.setWinningResultId(tmpTWinningResultId);
		 if (!StringUtils.isEmpty(tmpPrizePicture)){
			 resp.setPrizePicture(getHttpUrl(tmpPrizePicture));
		 }
		 resp.setResultCode(LuckyDrawResultCode.SUCCESS);
		 resp.setResultDesc("successfull");
		 resp.setPrizeCode(tmpPrizeCode);
	}

//	public static void main(String[] args) {
//	int winningSuccess = 0;
//	int winningfail = 0;
//	for (int i=0; i < 1000; i++){
//		 float[] tmpFloatArray = new float[]{0.0f, 0.1f,1.0f,10.f,20f};
//		 int tmpBase = 10000;
//		 int tmpRandNum = (int)(1+Math.random()*(tmpBase));
//		 int tmpIntOdds;
//		 int cumulativeBeforeNum = 0;
//		 int cumulativeAfterNum = 0;
//		 boolean winningFlag = false;
//		 for (float tmpFloat : tmpFloatArray){
//			 if (tmpFloat <= 0) continue;
//			 tmpIntOdds = (int) (tmpFloat *  100);
//			 cumulativeBeforeNum = cumulativeAfterNum;
//			 cumulativeAfterNum = cumulativeBeforeNum + tmpIntOdds;
//			 if (tmpRandNum >cumulativeBeforeNum && tmpRandNum <= cumulativeAfterNum){
//				 System.out.println(i +"--中奖了（" + tmpFloat +"）！");
//				 winningFlag = true;
//				 break;
//			 }
//		 }
//		if (winningFlag){
//			winningSuccess ++;
//		}else{
//			winningfail ++;
//		}
//	}
//	System.out.println("中奖人数：" + winningSuccess);
//	System.out.println("未中奖人数：" + winningfail);
//}
}
